#coding=utf8

from functools import partial
from flask import request, g

def set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None):
    if 'flask_cookies' not in g:
        g.flask_cookies = {}

    def op(resp):
        resp.set_cookie(key, value=value, max_age=max_age, expires=expires, path=path, domain=domain, secure=secure, httponly=httponly, samesite=samesite)

    g.flask_cookies[key] = op


def del_cookie(key):
    if 'flask_cookies' not in g:
        g.flask_cookies = {}

    def op(resp):
        resp.set_cookie(key, "", expires=0)

    g.flask_cookies[key] = op


def get_cookie(key, default=None):
    return request.cookies.get(key, default)


def save_cookies(resp):
    for fn in g.pop('flask_cookies', {}).values():
        fn(resp)

    return resp

